<template>
  <div class="main">
    <div id="leaflet" class="leaflet"></div>
  </div>
</template>

<script>
import L from "leaflet";
import geojson from "../assets/json/map1.json";
import setting from "../assets/json/map1-setting.json";

export default {
  data() {
    return {
      map: {
        lng: 114.502461,
        lat: 38.045474
      }
    };
  },
  methods: {
    init() {
      this.initMap();
      this.loadTileLayer();
      this.loadGeoJSON();
    },
    initMap() {
      this.map = L.map("leaflet", {
        center: [this.map.lat, this.map.lng],
        zoom: 13
      });
    },
    loadTileLayer() {
      L.tileLayer(
        "http://t{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={z}&TileRow={y}&TileCol={x}&style=default&format=tiles&tk=bebf738d00ce5ce52058e5d1619d4f5c",
        {
          maxZoom: 18,
          minZoom: 9,
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          detectRetina: true
        }
      ).addTo(this.map);

      L.tileLayer(
        "https://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=bebf738d00ce5ce52058e5d1619d4f5c",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"]
        }
      ).addTo(this.map);
    },
    loadGeoJSON() {
      let __this = this;
      let layer = new L.geoJSON(geojson, {
        coordsToLatLng: function(coords) {
          let wgs = __this.gps.gcj02ToWgs84(coords[1], coords[0]);
          return L.CRS.EPSG4326.unproject(L.point(wgs.lng, wgs.lat));
        },
        style: res => {
          let style = setting.find(item => {
            return res.properties.adcode === item.adcode;
          });
          if (!style) {
            style = {
              fillColor: "#000",
              fillOpacity: 0.4,
              color: "#ff0",
              weight: 4,
              pane: "mapPane"
            };
          }
          return style;
        }
      });
      this.geoJSONGroup = new L.LayerGroup();
      this.geoJSONGroup.addLayer(layer);
      this.geoJSONGroup.addTo(this.map);
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
.main
  position relative
  width 100%
  height 100%

  .leaflet
    position relative
    width 100%
    height 100%
</style>
